package rigo.ricard.pris.rs.ac.uns.dmi.cars.bean;

import java.io.Serializable;
import java.util.List;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;

import rigo.ricard.pris.rs.ac.uns.dmi.model.Advertising;
import rigo.ricard.pris.rs.ac.uns.dmi.service.AdvertisingLocalServiceUtil;
import rigo.ricard.pris.rs.ac.uns.dmi.util.CurrentUser;

import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.model.User;
import com.liferay.portlet.asset.service.AssetCategoryLocalServiceUtil;

@ManagedBean(name = "carsBean")
@ViewScoped
public class CarsBean implements Serializable {
	
	private static final Log log = LogFactoryUtil.getLog(CarsBean.class);

	private List<Advertising> advertisings = null;
	
	private Advertising selectedAd = null;
	
	public CarsBean() {
		//TODO just for user
		init();
	}
	
	public void init() {
		try {
			User user = CurrentUser.getCurrentUser(FacesContext.getCurrentInstance());
			if(user!=null) {
				advertisings = AdvertisingLocalServiceUtil.getAdverisignsByUserId(user.getUserId());
			}
		} catch (SystemException e) {
			log.error("error loading advertisings : "+e.getMessage());
		}
	}

	public String getManufacturerString(Advertising advertising) {
		try {
			return AssetCategoryLocalServiceUtil.getAssetCategory(advertising.getCarManufacturerId()).getName();
		} catch (Exception e) {
			return " - ";
		}
	}
	
	public String getModelString(Advertising advertising) {
		try {
			return AssetCategoryLocalServiceUtil.getAssetCategory(advertising.getCarModelId()).getName();
		} catch (Exception e) {
			return " - ";
		}
	}
	
	public void delete() {
		try {
			if(selectedAd!=null) {
				AdvertisingLocalServiceUtil.deleteAdvertising(selectedAd);
				init();
				FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Successfully deleted ad", ""));
			}
		} catch (Exception e) {
			log.error("error deleting ad : "+e.getMessage());
			FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error in deleting ad", ""));
		}
	}

	public List<Advertising> getAdvertisings() {
		return advertisings;
	}

	public void setAdvertisings(List<Advertising> advertisings) {
		this.advertisings = advertisings;
	}

	public Advertising getSelectedAd() {
		return selectedAd;
	}

	public void setSelectedAd(Advertising selectedAd) {
		this.selectedAd = selectedAd;
	}
}
